package com.resource.project.service.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.resource.project.common.HrUtils;
import com.resource.project.entity.*;
import com.resource.project.entity.system.Hr;
import com.resource.project.entity.system.HrRole;
import com.resource.project.entity.system.UserDetail;
import com.resource.project.mapper.*;
import com.resource.project.os.HrVo;
import com.resource.project.service.system.service.IHrService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.resource.project.service.system.service.IRoleService;
import com.resource.util.page.PageParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author resource
 * @since 2020-03-14
 */
@Service
@Transactional
public class HrServiceImpl extends ServiceImpl<HrMapper, Hr> implements IHrService {
    @Autowired
    private HrMapper hrMapper;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private HrRoleMapper hrRoleMapper;
    public RespBean hrReg(Hr hr) {
        //如果用户名存在，返回错误
        if (hrMapper.loadUserByUsername(hr.getUsername()) != null) {
            return RespBean.error("用户名存在");
        }
        String encode = passwordBcrypt(hr.getPassword());
        hr.setPassword(encode).setEnabled(true);
        if (save(hr)){
            HrRole hrRole = new HrRole();
            hrRole.setHrid(hr.getId());
            if(0==hr.getType()){
                //管理员
                hrRole.setRid(6);
            }else if (1==hr.getType()){
                //学生
                hrRole.setRid(3);
            }else {
                //教师
                hrRole.setRid(2);

            }
            hrRoleMapper.insert(hrRole);
            return RespBean.ok();
        }
        return RespBean.error("添加失败");
    }

    private String passwordBcrypt(String password){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder.encode(password);
    }


    public RespBean updateHr(Hr hr) {
        hrMapper.updateHr(hr);
        return RespBean.ok("更新成功");
    }

    private RespBean checkPwd(String password) {
        boolean flag = password.matches(".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*") ? false : true;
        if (!flag){
            return RespBean.error("密码含有非法字符");
        }
        return RespBean.ok();
    }

    public int updateHrRoles(Long hrId, Long[] rids) {
        int i = hrMapper.deleteRoleByHrId(hrId);
        return hrMapper.addRolesForHr(hrId, rids);
    }

    public int deleteHr(Long hrId) {
        return hrMapper.deleteHr(hrId);
    }

    public List<Hr> getAllHrExceptAdmin() {
        return hrMapper.getAllHr(HrUtils.getCurrentHr().getId());
    }
    public List<Hr> getAllHr() {
        return hrMapper.getAllHr(null);
    }

    HrVo toVo(Hr hr){
        if (hr!=null){
            HrVo vo = new HrVo();
            BeanUtils.copyProperties(hr,vo);
            return vo;
        }
        return null;
    }

    @Override
    public IPage<HrVo> page(PageParam pageParam, Hr hr) {
        QueryWrapper<Hr> wrapper = new QueryWrapper<>();
        wrapper.eq("type",1);
        if (hr!=null){
            if (hr.getName()!=null){
                wrapper.like("name",hr.getName());
            }
            if (StrUtil.isNotEmpty(hr.getTelephone())){
                wrapper.eq("telephone",hr.getTelephone());
            }
        }
        return page(pageParam.toMybaitsPage(),wrapper).convert(v->new HrVo().copyAttr(v));
    }

    @Override
    public UserDetail loadUserByUsername(String s) {
        Hr hr = hrMapper.loadUserByUsername(s);
        if (hr!=null){
            UserDetail detail = Convert.convert(UserDetail.class, hr);
            detail.setRoles(roleMapper.getRolesByHrId(hr.getId()));
            return detail;
        }
        return null;
    }

    @Override
    public boolean update(Long id,Boolean flag) {
        System.err.println(flag);
        Hr hr = hrMapper.selectById(id);
        if (hr==null){
            return false;
        }
        hr.setEnabled(flag);
        return hrMapper.updateById(hr)==1?true:false;
    }

    @Override
    public RespBean userInfo() {
        HrVo currentHr = HrUtils.getDetailHr();
        return RespBean.ok(currentHr);
    }

    @Override
    public Hr getByAccount(String account) {
        return getOne(Wrappers.<Hr>lambdaQuery().eq(StrUtil.isNotEmpty(account),Hr::getUsername,account));
    }

    @Override
    public RespBean forgetPassword(String email) {
        //发送右键
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("897949068@qq.com");//发送者
        msg.setTo(email);//接收者
        msg.setSubject("修改密码");//标题
        msg.setText("您正在重置密码，请继续..哈哈！！");//内容
        //javaMailSender.send(msg);
        return RespBean.ok();
    }

    @Override
    public RespBean resetPassword(Hr hr) {
        QueryWrapper<Hr> wrapper = new QueryWrapper<>();
        wrapper.eq("username",hr.getUsername()).eq("email",hr.getEmail());
        Hr one = getOne(wrapper);
        if (one==null){
            return RespBean.error("用户不存在");
        }
        String password = hr.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(password);
        if (updateById(one.setPassword(encode))){
            return RespBean.ok("重置成功！");
        }
        return RespBean.error("重置失败！");
    }

}
